<?php

namespace App\Http\Controllers\Wechat;

use App\Helpers\ApiResponseTrait;
use App\Model\UserWechat;
use App\Model\WeChat;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    use ApiResponseTrait;

    private $weChatUser;


    public function wechatLogin(Request $request)
    {
        $param = '';
        foreach ($request->all() as $key=>$val){
            $param .= '&'.$key.'='.rawurlencode($val);
        }

        $user = session('wechat.oauth_user'); // 拿到授权用户资料
        $user = $user['default'];

        $this->weChatUser = UserWechat::saveWeChatUser($user);   // 保存微信用户信息

        if($this->weChatUser) {
            $token = $this->beforeLogin();
            return redirect()->to($this->getLoginRedirectUrl($this->weChatUser->openid,$token,$param));
        }

        return redirect()->to($this->getLoginRedirectUrl('','',$param));
    }

    //登陆之前的操作
    private function beforeLogin()
    {
        $token = '';
        if($user = $this->weChatUser->user) {
            $token = auth()->login($user);
            $user->afterLogin();
        }
        return $token;
    }

    //获取登陆格式化跳转地址
    private function getLoginRedirectUrl($openid='',$token='',$param='')
    {
        return env('APP_FRONT') . '?token='.$token.'&openid='.$openid.$param;
    }

}
